package com.cloudm.technician.extensions

import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.widget.Toast
import com.cloudm.technician.ui.base.BaseActivity
import com.cloudm.technician.ui.base.BaseApplication
import com.orhanobut.logger.Logger

/**
 * 作者: wesley
 * 时间: 2017/11/20
 * 描述: 上下文的扩展函数
 */


val Context.baseApplication: BaseApplication?
    get() = applicationContext as? BaseApplication


private fun Context.finishSelf(finishSelf: Boolean) {
    if (finishSelf) {
        val activity = this as? BaseActivity ?: return
        activity.finish()
    }
}


/**
 * 界面跳转
 */
fun Context.openActivity(intent: Intent, finishSelf: Boolean = true) {
    startActivity(intent)
    finishSelf(finishSelf)
}


/**
 * 界面跳转
 */
fun <T> Context.openActivity(target: Class<T>, finishSelf: Boolean = true) {
    val intent = Intent(this, target)
    openActivity(intent, finishSelf)
}


/**
 * 弹出提示
 */
fun Context.toast(msg: String, duration: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(this, msg, duration).show()
}


/**
 * 判断是否有网络
 */
fun Context.isConnected(): Boolean {
    val value = getSystemService(Context.CONNECTIVITY_SERVICE)
    val manager = value as? ConnectivityManager ?: return false
    return manager.activeNetworkInfo?.isConnected ?: false
}


/**
 * 打印日志
 */
fun Context.logger_e(message: String, tag: String = packageName) {
    Logger.t(tag).e(message)
}


/**
 * 打印日志
 */
fun Context.logger_d(message: String, tag: String = packageName) {
    Logger.t(tag).d(message)
}

/**
 * 打印日志
 */
fun Context.logger_i(message: String, tag: String = packageName) {
    Logger.t(tag).i(message)
}

/**
 * 打印日志
 */
fun Context.logger_json(message: String, tag: String = packageName) {
    Logger.t(tag).json(message)
}